package com.xm.xmapp.customview;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.xm.xmapp.R;
import com.xm.xmapp.myinterface.MyDialogButton;

public class DateTimePickDialog extends Dialog implements OnDateChangedListener {

	private DatePicker datePicker;
	private TextView left, right, title, men, women;
	Activity activity;
	private String initDateTime;
	private String dateTime;
	private MyDialogButton in;
	private LinearLayout lin, lin1;
	private int flag;

	public DateTimePickDialog(Context context, int theme) {
		super(context, theme);
	}

	public DateTimePickDialog(Activity activity, MyDialogButton in, int flag) {
		this(activity, R.style.share_Dialog);
		this.activity = activity;
		this.in = in;
		this.flag = flag;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub

		return super.onTouchEvent(event);

	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dialog_datetimepicker);
		datePicker = (DatePicker) findViewById(R.id.datepicker);
		left = (TextView) findViewById(R.id.left);
		right = (TextView) findViewById(R.id.right);
		lin = (LinearLayout) findViewById(R.id.lin);
		lin1 = (LinearLayout) findViewById(R.id.lin1);
		title = (TextView) findViewById(R.id.title);
		men = (TextView) findViewById(R.id.men);
		women = (TextView) findViewById(R.id.women);
		if (flag == 2) {
			lin.setVisibility(View.VISIBLE);
			datePicker.setVisibility(View.GONE);
			lin1.setVisibility(View.GONE);
			title.setText("请选择您的性别");
		} else {
			title.setText("请输入您的出生日期");
			lin.setVisibility(View.GONE);
			datePicker.setVisibility(View.VISIBLE);
			init(datePicker);
		}

		Window window = getWindow();
		WindowManager.LayoutParams wl = window.getAttributes();
		wl.alpha = 1.0f;

		wl.gravity = Gravity.BOTTOM;
		WindowManager wm = activity.getWindowManager();
		wl.width = wm.getDefaultDisplay().getWidth();
		window.setAttributes(wl);
		setCancelable(true);
		setCanceledOnTouchOutside(true);

		men.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (in != null)
					in.setTitle(flag, "男");
				dismiss();
			}
		});
		women.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (in != null)
					in.setTitle(flag, "女");
				dismiss();
			}
		});
		left.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

				dismiss();
			}
		});
		right.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				// dateTime
				// Tools.showMessage(dateTime);
				if (in != null)
					in.setTitle(flag, dateTime);

				dismiss();
			}
		});

	}

	public void init(DatePicker datePicker) {
		Calendar calendar = Calendar.getInstance();
		if (!(null == initDateTime || "".equals(initDateTime))) {
			calendar = this.getCalendarByInintData(initDateTime);
		} else {
			initDateTime = calendar.get(Calendar.YEAR) + "-"
					+ calendar.get(Calendar.MONTH) + "-"
					+ calendar.get(Calendar.DAY_OF_MONTH);
			dateTime = calendar.get(Calendar.YEAR) + "-"
					+ (calendar.get(Calendar.MONTH) + 1) + "-"
					+ calendar.get(Calendar.DAY_OF_MONTH);

		}

		datePicker.init(calendar.get(Calendar.YEAR),
				calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH), this);

	}

	/**
	 * 实现将初始日期时间2012年07月02日 16:45 拆分成年 月 日 时 分 秒,并赋值给calendar
	 * 
	 * @param initDateTime
	 *            初始日期时间值 字符串型
	 * @return Calendar
	 */
	private Calendar getCalendarByInintData(String initDateTime) {
		Calendar calendar = Calendar.getInstance();

		// 将初始日期时间2012年07月02日 16:45 拆分成年 月 日 时 分 秒
		String date = spliteString(initDateTime, "日", "index", "front"); // 日期
		String time = spliteString(initDateTime, "日", "index", "back"); // 时间

		String yearStr = spliteString(date, "年", "index", "front"); // 年份
		String monthAndDay = spliteString(date, "年", "index", "back"); // 月日

		String monthStr = spliteString(monthAndDay, "月", "index", "front"); // 月
		String dayStr = spliteString(monthAndDay, "月", "index", "back"); // 日

		String hourStr = spliteString(time, ":", "index", "front"); // 时
		String minuteStr = spliteString(time, ":", "index", "back"); // 分

		int currentYear = Integer.valueOf(yearStr.trim()).intValue();
		int currentMonth = Integer.valueOf(monthStr.trim()).intValue() - 1;
		int currentDay = Integer.valueOf(dayStr.trim()).intValue();
		int currentHour = Integer.valueOf(hourStr.trim()).intValue();
		int currentMinute = Integer.valueOf(minuteStr.trim()).intValue();

		calendar.set(currentYear, currentMonth, currentDay, currentHour,
				currentMinute);
		return calendar;
	}

	/**
	 * 截取子串
	 * 
	 * @param srcStr
	 *            源串
	 * @param pattern
	 *            匹配模式
	 * @param indexOrLast
	 * @param frontOrBack
	 * @return
	 */
	public static String spliteString(String srcStr, String pattern,
			String indexOrLast, String frontOrBack) {
		String result = "";
		int loc = -1;
		if (indexOrLast.equalsIgnoreCase("index")) {
			loc = srcStr.indexOf(pattern); // 取得字符串第一次出现的位置
		} else {
			loc = srcStr.lastIndexOf(pattern); // 最后一个匹配串的位置
		}
		if (frontOrBack.equalsIgnoreCase("front")) {
			if (loc != -1)
				result = srcStr.substring(0, loc); // 截取子串
		} else {
			if (loc != -1)
				result = srcStr.substring(loc + 1, srcStr.length()); // 截取子串
		}
		return result;
	}

	@Override
	public void onDateChanged(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		// TODO Auto-generated method stub
		// 获得日历实例

		if (isDateAfter(view)) {
			Calendar mCalendar = Calendar.getInstance();
			view.init(mCalendar.get(Calendar.YEAR),
					mCalendar.get(Calendar.MONTH),
					mCalendar.get(Calendar.DAY_OF_MONTH), this);
		} else {

			Calendar calendar = Calendar.getInstance();

			calendar.set(datePicker.getYear(), datePicker.getMonth(),
					datePicker.getDayOfMonth(), 0, 0);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

			dateTime = sdf.format(calendar.getTime());
			this.setTitle(dateTime);
		}
	}

	private boolean isDateAfter(DatePicker tempView) {
		Calendar mCalendar = Calendar.getInstance();
		Calendar tempCalendar = Calendar.getInstance();
		tempCalendar.set(tempView.getYear(), tempView.getMonth(),
				tempView.getDayOfMonth(), 0, 0, 0);
		if (tempCalendar.after(mCalendar))
			return true;
		else
			return false;
	}
}
